package com.easy.framework.security.handler;

import com.alibaba.fastjson2.JSON;
import com.easy.framework.common.constant.I18NConstants;
import com.easy.framework.common.model.R;
import com.easy.framework.common.utils.I18NUtils;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Log4j2
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    @SneakyThrows
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.getWriter().write(JSON.toJSONString(R.fail(HttpStatus.FORBIDDEN.value(), I18NUtils.message(I18NConstants.AUTHENTICATION_DENIED_PERMISSION))));
    }
}
